<template>
  <div class="operUser">

    <div class="func-block" @click="addUserDialog = true">
      <el-button type="primary" plain icon="el-icon-circle-plus-outline">新增用户</el-button>
    </div>

    <div class="func-block" @click="searchUserDialog = true">
      <el-button type="warning" plain icon="el-icon-search">精准筛选</el-button>
    </div>

    <div class="func-block" @click="getUserList()">
      <el-button type="primary">清除筛选</el-button>
    </div>

    <div class="user-table">
      <el-table v-loading="tableLoader" :data="userList">
        <el-table-column prop="userId" label="用户ID" width="100" align="center" show-overflow-tooltip>
        </el-table-column>

        <el-table-column prop="account" key="account" label="账号" width="150" align="center" show-overflow-tooltip>
        </el-table-column>

        <el-table-column prop="nickname" key="nickname" label="用户名" width="150" align="center" show-overflow-tooltip>
        </el-table-column>

        <el-table-column prop="email" key="email" label="邮箱" width="150" align="center" show-overflow-tooltip>
        </el-table-column>

        <el-table-column prop="gender" key="gender" label="性别" width="80" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.gender == 0" type="danger">女</el-tag>
            <el-tag v-else-if="scope.row.gender == 1">男</el-tag>
            <el-tag v-else type="info">保密</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="账号状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 0" type="success">正常</el-tag>
            <el-tag v-else type="danger">冻结</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="loginIp" key="loginIp" label="最后一次登录IP" width="130" align="center">
        </el-table-column>

        <el-table-column label="最后一次登录时间" width="180" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{
              scope.row.loginTime
              | dateFormat("yyyy-mm-dd hh:mm:ss")
            }}
          </template>
        </el-table-column>

        <el-table-column label="注册时间" width="180" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{
              scope.row.registerTime
              | dateFormat("yyyy-mm-dd hh:mm:ss")
            }}
          </template>
        </el-table-column>

        <el-table-column width="300" align="center" label="操作">
          <template slot-scope="scope">
            <el-button class="tableButton" @click="getUserById(scope.row.userId)" type="primary" size="small">查看
            </el-button>
            <el-button class="tableButton" @click="getUpdateUserInfo(scope.row.userId)" type="success" size="small">编辑
            </el-button>
            <el-button class="tableButton" @click="handleDelete(scope.row.userId)" type="danger" size="small">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 每页8条 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getUserList" />

      <!-- 新增用户 -->
      <el-dialog title="新增用户" :visible.sync="addUserDialog" width="30%" center>
        <div class="add-user-form">
          <el-form ref="addUserForm" :model="addUserForm" :rules="rules" label-width="70px">
            <el-form-item class="addUserItem" label="账号" prop="account">
              <el-input class="addUserInput" prefix-icon="el-icon-user-solid" type="text"
                placeholder="账号[10,15]小写字母开头，其它数字" v-model="addUserForm.account" />
            </el-form-item>

            <el-form-item class="addUserItem" label="密码" prop="password">
              <el-input class="addUserInput" prefix-icon="el-icon-lock" type="password" placeholder="密码[6,20]"
                v-model="addUserForm.password" />
            </el-form-item>

            <el-form-item class="addUserItem" label="邮箱" prop="email">
              <el-input class="addUserInput" prefix-icon="el-icon-message" type="email" placeholder="请输入邮箱"
                v-model="addUserForm.email" />
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserDialog = false">取 消</el-button>
          <el-button type="success" @click="insertUser('addUserForm')" v-if="!addLoader">添 加</el-button>
          <el-button type="success" :loading="addLoader" v-else>添 加 中...</el-button>
        </span>
      </el-dialog>

      <!-- 查询用户-->
      <el-dialog title="筛选查询" :visible.sync="searchUserDialog" width="40%" center>
        <el-form ref="searchUserForm" :model="searchUserForm" label-width="80px">
          <el-form-item label="用户编号">
            <el-input v-model="searchUserForm.userId"></el-input>
          </el-form-item>
          <el-form-item label="用户帐号">
            <el-input v-model="searchUserForm.account"></el-input>
          </el-form-item>
          <el-form-item label="用户名称">
            <el-input v-model="searchUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱">
            <el-input v-model="searchUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="用户性别">
            <el-select v-model="searchUserForm.gender" placeholder="请选择用户性别">
              <el-option v-for="item in genderOpt" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="账号状态">
            <el-select v-model="searchUserForm.status" placeholder="请选择账号状态">
              <el-option v-for="item in accountStatusOpt" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="登录时间">
            <el-col :span="8">
              <el-date-picker type="date" placeholder="选择起始日期" v-model="searchUserForm.loginStartDate"
                style="width: 100%;" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </el-col>
            <el-col style="text-align: center;" :span="1">-</el-col>
            <el-col :span="8">
              <el-date-picker placeholder="选择截至日期" v-model="searchUserForm.loginEndDate" style="width: 100%;"
                format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="注册时间">
            <el-col :span="8">
              <el-date-picker type="date" placeholder="选择起始日期" v-model="searchUserForm.registerStartDate"
                style="width: 100%;" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </el-col>
            <el-col style="text-align: center;" :span="1">-</el-col>
            <el-col :span="8">
              <el-date-picker placeholder="选择截至日期" v-model="searchUserForm.registerEndDate" style="width: 100%;"
                format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </el-col>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="searchUserDialog = false">取 消</el-button>
          <el-button type="warning" @click="searchUser()">查 询</el-button>
        </span>
      </el-dialog>

      <!-- 查看用户详情 -->
      <el-dialog title="用户详情" :visible.sync="dialogDetailVisible">
        <div class="user-detail-block">
          <div class="user-avatar">
            <el-avatar :size="70" :src="userDetail.avatar"></el-avatar>
          </div>

          <div class="user-main-detail">
            <el-descriptions direction="vertical" :column="4" border>
              <el-descriptions-item label="账号">{{
                userDetail.account
              }}</el-descriptions-item>
              <el-descriptions-item label="用户名">{{
                userDetail.nickname
              }}</el-descriptions-item>
              <el-descriptions-item label="账号状态">
                <el-tag v-if="userDetail.status == 0" type="success">正常</el-tag>
                <el-tag v-else type="danger">冻结</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="性别">
                <el-tag v-if="userDetail.gender == 0" type="danger">女</el-tag>
                <el-tag v-else-if="userDetail.gender == 1">男</el-tag>
                <el-tag v-else type="info">保密</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="邮箱">{{
                userDetail.email
              }}</el-descriptions-item>
              <el-descriptions-item label="粉丝数量">{{
                userDetail.fans
              }}</el-descriptions-item>
              <el-descriptions-item label="关注数量">{{
                userDetail.subs
              }}</el-descriptions-item>
              <el-descriptions-item label="发布视频数">{{
                userDetail.publishCount
              }}</el-descriptions-item>
              <el-descriptions-item label="发表评论数">{{
                userDetail.commentCount + userDetail.replyCount
              }}</el-descriptions-item>
              <el-descriptions-item label="个人简介" :span="3">{{ userDetail.sign }}
              </el-descriptions-item>
              <el-descriptions-item label="登录IP">{{
                userDetail.loginIp
              }}</el-descriptions-item>
              <el-descriptions-item label="最后一次登录时间">
                {{
                  userDetail.loginTime
                  | dateFormat("yyyy-mm-dd hh:mm:ss")
                }}
              </el-descriptions-item>
              <el-descriptions-item label="注册时间">
                {{
                  userDetail.registerTime
                  | dateFormat("yyyy-mm-dd hh:mm:ss")
                }}
              </el-descriptions-item>
              <el-descriptions-item label="修改信息时间">
                {{
                  userDetail.modifyTime
                  | dateFormat("yyyy-mm-dd hh:mm:ss")
                }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </el-dialog>

      <!-- 编辑用户 -->
      <el-dialog title="编辑用户" :visible.sync="dialogFormVisible">
        <el-form ref="modifyUserForm" :model="modifyForm" :rules="modifyFormRule" label-width="70px">
          <el-form-item label="账号" prop="userInfo.account">
            <el-input prefix-icon="el-icon-user-solid" type="text" placeholder="账号[10,15]小写字母开头，其它数字"
              v-model="modifyForm.userInfo.account" />
          </el-form-item>

          <el-form-item label="用户名" prop="userInfo.nickname">
            <el-input prefix-icon="el-icon-user-solid" type="text" placeholder="用户名[2,20]"
              v-model="modifyForm.userInfo.nickname" />
          </el-form-item>

          <el-form-item label="密码" prop="userInfo.password">
            <el-input prefix-icon="el-icon-lock" type="password" placeholder="密码[6,20]"
              v-model="modifyForm.userInfo.password" />
          </el-form-item>

          <el-form-item label="邮箱" prop="userInfo.email">
            <el-input prefix-icon="el-icon-message" type="email" placeholder="请输入邮箱"
              v-model="modifyForm.userInfo.email" />
          </el-form-item>

          <el-form-item label="账号状态" prop="userInfo.status">
            <el-switch style="display: inline-block" v-model="modifyForm.userInfo.status" active-value="0"
              inactive-value="1" active-color="#13ce66" inactive-color="#ff4949" active-text="正常" inactive-text="冻结">
            </el-switch>
          </el-form-item>

          <el-form-item>
            <el-button :loading="updateLoader" type="success" v-on:click="onSubmit('modifyUserForm')">
              <span v-if="!updateLoader">修 改</span>
              <span v-else>修 改 中...</span>
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  addUser,
  deleteUserByUid,
  getUserByUid,
  getUserList,
  getModifyUserByUid,
  updateUserInfo,
} from "@/api/user";
import { Message } from "element-ui";

export default {
  name: "operUser",

  data() {
    return {
      addUserDialog: false,

      searchUserDialog: false,

      searchUserForm: {
        userId: '',
        account: '',
        username: '',
        email: '',
        gender: '',
        status: '',
        loginStartDate: '',
        loginEndDate: '',
        registerStartDate: '',
        registerEndDate: ''
      },

      genderOpt: [
        {
          label: '女',
          value: '0'
        },
        {
          label: '男',
          value: '1'
        },
        {
          label: '保密',
          value: '2'
        },
      ],

      accountStatusOpt: [
        {
          label: '正常',
          value: '0'
        },
        {
          label: '冻结',
          value: '1'
        }
      ],

      userList: null,
      dialogFormVisible: false,
      dialogDetailVisible: false,
      total: 0,
      search: "",

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5
      },

      // 用户详情
      userDetail: {},

      // 编辑用户
      modifyForm: {
        userInfo: {
          userId: '',
          account: '',
          nickname: '',
          password: '',
          email: '',
          status: ''
        }
      },

      modifyFormRule: {
        userInfo: {
          account: [
            {
              required: true,
              message: "账号不可为空",
              trigger: "blur",
            },
          ],
          nickname: [
            {
              required: true,
              message: "用户名不可为空",
              trigger: "blur",
            },
          ],
          password: [
            {
              required: true,
              message: "密码不可为空",
              trigger: "blur",
            },
          ],
          email: [
            {
              required: true,
              message: "邮箱不可为空",
              trigger: "blur",
            },
          ],
        },
      },

      addUserForm: {
        account: "",
        password: "",
        email: "",
      },

      rules: {
        account: [
          {
            required: true,
            message: "账号不可为空",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不可为空",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "邮箱不可为空",
            trigger: "blur",
          },
        ],
      },
      tableLoader: false,
      addLoader: false,
      updateLoader: false
    };
  },

  created() {
    this.tableLoader = true;
    this.getUserList();
  },
  methods: {

    searchUser() {
      if (!Number.isInteger(Number(this.searchUserForm.userId))) {
        Message.error('用户编号是数字')
        return false
      }
      this.searchUserForm.userId = Number(this.searchUserForm.userId)
      this.searchUserDialog = false
      this.tableLoader = true;
      this.getUserList();
      this.searchUserForm = Object.assign({}, {
        userId: '',
        account: '',
        username: '',
        email: '',
        gender: '',
        status: '',
        loginStartDate: '',
        loginEndDate: '',
        registerStartDate: '',
        registerEndDate: ''
      })
    },

    insertUser(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addLoader = true;
          addUser(this.addUserForm).then((res) => {
            if (res && res.code === 200) {
              Message.success("添加成功");
              this.$refs[formName].resetFields();
              this.addUserDialog = false
              this.tableLoader = true;
              this.getUserList();
            }
            this.addLoader = false;
          })
        } else {
          this.addLoader = false;
          return false;
        }
      });
    },

    // 获取用户列表
    getUserList() {
      getUserList(this.queryParams, this.searchUserForm).then((res) => {
        this.tableLoader = false;
        this.userList = res.rows;
        this.total = res.total;
      });
    },

    // 获取用户详情
    getUserById(uid) {
      getUserByUid(uid).then((res) => {
        this.dialogDetailVisible = true;
        this.userDetail = res.data;
      });
    },

    // 获取编辑用户详情
    getUpdateUserInfo(uid) {
      getModifyUserByUid(uid).then((res) => {
        this.dialogFormVisible = true;
        this.modifyForm.userInfo = res.data;
      });
    },

    // 编辑用户
    onSubmit(formName) {
      // 为表单绑定验证功能
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.updateLoader = true;
          updateUserInfo(this.modifyForm.userInfo).then((res) => {
            if (res) {
              Message.success("修改成功");
              this.updateLoader = false;
              this.dialogFormVisible = false
              this.tableLoader = true;
              this.getUserList();
            } else this.updateLoader = false;
          });
        } else {
          this.updateLoader = false;
          return false;
        }
      });
    },

    // 删除用户
    handleDelete(uid) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteUserByUid(uid).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.tableLoader = true;
            this.getUserList();
          }
        });
      });
    },
  },

  filters: {
    dateFormat: function (val, args) {
      if (val) {
        var dt = new Date(val);
        var year = dt.getFullYear();
        var month = ("0" + (dt.getMonth() + 1)).slice(-2);
        var day = ("0" + dt.getDate()).slice(-2);
        if (args.toLowerCase() === "yyyy-mm-dd") {
          return year + "-" + month + "-" + day;
        } else {
          var hour = ("0" + dt.getHours()).slice(-2);
          var min = ("0" + dt.getMinutes()).slice(-2);
          var sec = ("0" + dt.getSeconds()).slice(-2);
          return (
            year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec
          );
        }
      } else {
        return '';
      }
    },
  },

  watch: {
    search(val) {
      this.queryParams.username = val;
      this.getUserList();
    },
  },
};
</script>

<style lang="scss" scoped>
.func-block {
  margin-bottom: 20px;
  display: inline-block;
  margin-right: 20px;
}

.tableButton {
  margin-right: 8px;
}

.user-detail-block {
  text-align: center;
}
</style>
